package com.yycwxt.modules.admin.cwfy;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.yycwxt.common.BaseService;
import com.yycwxt.domain.Cwfy;
import com.yycwxt.domain.OperateFee;
import com.yycwxt.modules.admin.data_import.AccountData;
import com.yycwxt.modules.admin.data_import.ERPStoreOrder;
import lombok.SneakyThrows;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class CwfyService extends BaseService<CwfyMapper, Cwfy> {

    private CwfyMapper cwfyMapper;


    public CwfyService(CwfyMapper cwfyMapper){
        this.cwfyMapper = cwfyMapper;
    }

    @SneakyThrows
    public boolean importFileToDB(boolean deleteHistory, MultipartFile file) {
        if (deleteHistory) {
            this.remove(null);
        }
        EasyExcel.read(file.getInputStream(), OperateFee.class, new ReadListener<Cwfy>() {

            private static final int BATCH_SIZE = 1000;
            private List<Cwfy> ls = Lists.newArrayList();

            @Override
            public void invoke(Cwfy data, AnalysisContext context) {
                //System.err.println(data);
                ls.add(data);
                if (ls.size() >= BATCH_SIZE) {
                    CwfyService.this.saveBatch(ls);
                    ls.clear();
                }
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                CwfyService.this.saveBatch(ls);
            }
        }).sheet().doRead();
        return true;
    }

    // 下载源文件
    public List<String> getCwfyUrl(){
        return cwfyMapper.getCwfyUrl();
    }

    public List<Map<String, Object>> getcwfy(int zq){
        return cwfyMapper.getcwfy(zq);
    }

    @SneakyThrows
    @Transactional
    public void impCwfy(MultipartFile file) {
        EasyExcel.read(file.getInputStream(), Cwfy.class, new ReadListener<Cwfy>() {

            private static final int BATCH_SIZE = 1000;

            @Override
            public void invoke(Cwfy data, AnalysisContext context) {
                // 执行存储过程
                cwfyMapper.impCwfy(
                        AccountData.getAccountDate(),
                        data.getKm(), data.getJe(), data.getFtlx()
                );
            }

            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {

            }
        }).sheet().doRead();
    }
}
